import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, InputNumber, Select, Switch, message, Upload, Button, Space } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { createLesson, updateLesson, getCourseChapters } from '@/services/courseManagementApi';
import { uploadVideo, uploadAudio } from '@/services/systemManagementApi';

const { TextArea } = Input;
const { Option } = Select;

interface LessonFormProps {
  visible: boolean;
  mode: 'create' | 'edit';
  courseId: number;
  initialValues?: COURSE.LessonModel;
  onCancel: () => void;
  onSuccess: () => void;
}

const LessonForm: React.FC<LessonFormProps> = ({
  visible,
  mode,
  courseId,
  initialValues,
  onCancel,
  onSuccess,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [chapters, setChapters] = useState<COURSE.ChapterModel[]>([]);
  const [videoUploading, setVideoUploading] = useState(false);
  const [audioUploading, setAudioUploading] = useState(false);
  const [isAutoDuration, setIsAutoDuration] = useState(false); // 标记是否为自动计算的时长

  useEffect(() => {
    if (visible) {
      loadChapters();
      setIsAutoDuration(false); // 重置自动计算标记
      if (mode === 'edit' && initialValues) {
        form.setFieldsValue({
          ...initialValues,
          duration: Math.floor(initialValues.duration / 60), // 转换为分钟
        });
      } else {
        form.resetFields();
      }
    }
  }, [visible, mode, initialValues, form]);

  const loadChapters = async () => {
    try {
      const response = await getCourseChapters(courseId);
      setChapters(response.data || []);
    } catch (error) {
      console.error('加载章节失败:', error);
    }
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      // 转换时长为秒
      const submitData = {
        ...values,
        duration: values.duration * 60,
      };

      if (mode === 'create') {
        await createLesson(courseId, submitData);
        message.success('课时创建成功');
      } else {
        await updateLesson(initialValues!.id, submitData);
        message.success('课时更新成功');
      }

      onSuccess();
    } catch (error) {
      message.error(mode === 'create' ? '课时创建失败' : '课时更新失败');
    } finally {
      setLoading(false);
    }
  };

  const handleVideoUpload = async (file: File) => {
    setVideoUploading(true);
    try {
      const response = await uploadVideo(file);

      // 设置视频地址
      form.setFieldValue('video_url', response.data.url);

      // 如果后端返回了视频时长，自动计算并设置课时时长（转换为分钟）
      if (response.data.duration) {
        const durationInMinutes = Math.ceil(response.data.duration / 60); // 向上取整到分钟
        form.setFieldValue('duration', durationInMinutes);
        setIsAutoDuration(true); // 标记为自动计算的时长
        message.success(`视频上传成功，自动设置课时时长为 ${durationInMinutes} 分钟`);
      } else {
        message.success('视频上传成功');
      }
    } catch (error) {
      message.error('视频上传失败');
    } finally {
      setVideoUploading(false);
    }
    return false;
  };

  const handleAudioUpload = async (file: File) => {
    setAudioUploading(true);
    try {
      const response = await uploadAudio(file);
      form.setFieldValue('audio_url', response.data.url);

      message.success('音频上传成功');
    } catch (error) {
      message.error('音频上传失败');
    } finally {
      setAudioUploading(false);
    }
    return false;
  };

  return (
    <Modal
      title={mode === 'create' ? '添加课时' : '编辑课时'}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      width={600}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          is_free: false,
          is_active: true,
          sort_order: 10,
        }}
      >
        <Form.Item
          name="chapter_id"
          label="所属章节"
          help="可选，不选择则直接属于课程"
        >
          <Select placeholder="选择章节（可选）" allowClear>
            {chapters.map((chapter) => (
              <Option key={chapter.id} value={chapter.id}>
                {chapter.title}
              </Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          name="title"
          label="课时标题"
          rules={[{ required: true, message: '请输入课时标题' }]}
        >
          <Input placeholder="请输入课时标题" />
        </Form.Item>

        <Form.Item name="description" label="课时描述">
          <TextArea rows={3} placeholder="请输入课时描述" />
        </Form.Item>

        <Form.Item name="video_url" label="视频地址">
          <Space.Compact style={{ width: '100%' }}>
            <Input
              style={{ width: 'calc(100% - 100px)' }}
              placeholder={'请输入视频地址或上传视频文件'}
              value={form.getFieldValue('video_url')}
            />
            <Upload
              beforeUpload={handleVideoUpload}
              showUploadList={false}
              accept="video/*"
            >
              <Button
                loading={videoUploading}
                icon={<UploadOutlined />}
                style={{ width: 100 }}
              >
                上传视频
              </Button>
            </Upload>
          </Space.Compact>
        </Form.Item>

        <Form.Item name="audio_url" label="音频地址">
          <Space.Compact style={{ width: '100%' }}>
            <Input
              style={{ width: 'calc(100% - 100px)' }}
              placeholder="请输入音频地址或上传音频文件"
              value={form.getFieldValue('audio_url')}
            />
            <Upload
              beforeUpload={handleAudioUpload}
              showUploadList={false}
              accept="audio/*"
            >
              <Button
                loading={audioUploading}
                icon={<UploadOutlined />}
                style={{ width: 100 }}
              >
                上传音频
              </Button>
            </Upload>
          </Space.Compact>
        </Form.Item>

        <Form.Item
          name="duration"
          label="课时时长（分钟）"
          rules={[{ required: true, message: '请输入课时时长' }]}
          extra={
            isAutoDuration
              ? "✅ 已根据视频时长自动计算，可手动修改"
              : "上传视频后将自动计算时长，也可手动输入"
          }
        >
          <InputNumber
            min={1}
            max={999}
            placeholder="请输入课时时长或上传视频自动获取"
            style={{ width: '100%' }}
            onChange={() => {
              // 当用户手动修改时，清除自动计算标记
              if (isAutoDuration) {
                setIsAutoDuration(false);
              }
            }}
          />
        </Form.Item>

        <Form.Item
          name="sort_order"
          label="排序"
          rules={[{ required: true, message: '请输入排序值' }]}
        >
          <InputNumber
            min={1}
            placeholder="请输入排序值"
            style={{ width: '100%' }}
          />
        </Form.Item>

        <Form.Item name="is_free" label="免费课时" valuePropName="checked">
          <Switch />
        </Form.Item>

        <Form.Item name="is_active" label="启用状态" valuePropName="checked">
          <Switch />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default LessonForm;
